package com.lty.controller;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lty.common.BaseResponse;
import com.lty.common.DeleteRequest;
import com.lty.common.ErrorCode;
import com.lty.common.PageRequest;
import com.lty.common.ResultUtils;
import com.lty.exception.BusinessException;
import com.lty.model.dto.project.ProjectTemplateRefRequest;
import com.lty.model.entity.ProjectTemplateRef;
import com.lty.service.ProjectTemplateRefService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lty
 */
@Slf4j
@RestController
@RequestMapping("/projectTemplateRef")
public class ProjectTemplateRefController {

    @Resource
    private ProjectTemplateRefService projectTemplateRefService;


    @ApiOperation(value = "添加项目模板关联")
    @PostMapping("/add")
    @Transactional
    public BaseResponse<Boolean> addProjectTemplateRef(@RequestBody ProjectTemplateRefRequest request) {
        if (ObjectUtils.isEmpty(request.getProjectId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "项目id不能为空");
        }
        if (ObjectUtils.isEmpty(request.getTemplateId()) || request.getTemplateId().size() == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "模板id不能为空");
        }
        List<Long> templateId = request.getTemplateId();
        List<ProjectTemplateRef> list = projectTemplateRefService.list(new LambdaQueryWrapper<ProjectTemplateRef>().eq(ProjectTemplateRef::getProjectId, request.getProjectId()));
        List<Long> existTemplateIds = list.stream().map(ProjectTemplateRef::getTemplateId).distinct().collect(Collectors.toList());
        templateId.removeAll(existTemplateIds);
        // 如果没有需要添加的模板 ID，直接返回成功
        if (templateId.isEmpty()) {
            log.info("没有需要添加的模板id");
            return ResultUtils.success(true);
        }
        List<ProjectTemplateRef> saveList = new ArrayList<>();
        for (Long id : templateId) {
            ProjectTemplateRef projectTemplateRef = new ProjectTemplateRef();
            projectTemplateRef.setProjectId(request.getProjectId());
            projectTemplateRef.setTemplateId(id);
            saveList.add(projectTemplateRef);
        }
        boolean save = projectTemplateRefService.saveBatch(saveList);
        return ResultUtils.success(save);
    }


    @ApiOperation(value = "修改")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateProjectTemplateRef(@RequestBody ProjectTemplateRef projectTemplateRefUpdateRequest) {
        if (projectTemplateRefUpdateRequest == null || projectTemplateRefUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        ProjectTemplateRef projectTemplateRef = new ProjectTemplateRef();
        BeanUtils.copyProperties(projectTemplateRefUpdateRequest, projectTemplateRef);
        ProjectTemplateRef oldProjectTemplateRef = projectTemplateRefService.getById(projectTemplateRefUpdateRequest.getId());
        if (oldProjectTemplateRef == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = projectTemplateRefService.updateById(projectTemplateRef);
        return ResultUtils.success(result);
    }

    @ApiOperation(value = "通过id获取")
    @GetMapping(value = "/get/{id}")
    public BaseResponse<ProjectTemplateRef> getByProjectTemplateRefId(@PathVariable Long id) {
        if (id <= 0) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ProjectTemplateRef projectTemplateRef = projectTemplateRefService.getById(id);
        return ResultUtils.success(projectTemplateRef);
    }

    @ApiOperation(value = "列表获取")
    @GetMapping(value = "/list")
    public BaseResponse<List<ProjectTemplateRef>> listProjectTemplateRef(ProjectTemplateRef projectTemplateRef) {
        Wrapper<ProjectTemplateRef> qw = this.buildQueryWrapper(projectTemplateRef);
        List<ProjectTemplateRef> projectTemplateRefList = projectTemplateRefService.list(qw);
        return ResultUtils.success(projectTemplateRefList);
    }

    @ApiOperation(value = "分页获取")
    @GetMapping(value = "/list/page")
    public BaseResponse<Page<ProjectTemplateRef>> listProjectTemplateRefByPage(PageRequest pageRequest, ProjectTemplateRef projectTemplateRef) {
        // 分页基本字段
        long current = pageRequest.getCurrent();
        long size = pageRequest.getPageSize();
        // 反爬虫
        if (size > 100) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "查询数量过多");
        }
        Page<ProjectTemplateRef> page = new Page<>(current,size);
        Page<ProjectTemplateRef> projectTemplateRefPage = projectTemplateRefService.page(page, this.buildQueryWrapper(projectTemplateRef));
        return ResultUtils.success(projectTemplateRefPage);
    }

    @ApiOperation(value = "删除")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteProjectTemplateRef(@RequestBody DeleteRequest deleteRequest) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        ProjectTemplateRef oldProjectTemplateRef = projectTemplateRefService.getById(id);
        if (oldProjectTemplateRef == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean b = projectTemplateRefService.removeById(id);
        return ResultUtils.success(b);
    }
    
    public Wrapper<ProjectTemplateRef> buildQueryWrapper(ProjectTemplateRef projectTemplateRef) {
        QueryWrapper<ProjectTemplateRef> qw = new QueryWrapper<>();
        // TODO 添加查询条件

        return qw;
    }
}
